'use strict';
const path = require('path')
const npminstall = require('npminstall')
const fse = require('fs-extra')
const pkgDir = require('pkg-dir').sync
const pathExists = require('path-exists').sync
const {isObject} = require('@imooc-cli-dev-dq/utils')
const formatPath = require('@imooc-cli-dev-dq/format-path')
const {getDefaultRegistry, getNpmLatestVersion} = require('@imooc-cli-dev-dq/get-npm-info')
class Package {
    constructor(options) {

        if (!options || !isObject(options)) {
            throw new Error('Package类的options参数不能为空！')
        }
        console.log('启动 package')
        // package的目标路径
        this.targetPath = options.targetPath
        // 缓存package的路径
        this.storeDir = options.storeDir
        // package的存储路径
        // this.storePath = options.storePath
        // package的name
        this.packageName = options.packageName;
        // versions
        this.packageVersion = options.packageVersion
        // package的缓存目录前缀
        this.cacheFilePathPrefix = this.packageName.replace('/', '_')
    }
    async prepare() {
        if (this.storeDir && !pathExists(this.storeDir)) {
            fse.mkdirpSync(this.storeDir)
        }
        if (this.packageVersion === 'latest') {
            this.packageVersion =  await getNpmLatestVersion(this.packageName)
            
        }
        // _@imooc-cli_init@1.1.2@@imooc-cli/
        // @imooc-cli/init 1.1.2
    }
    get cacaeFilePath() {
        return path.resolve(this.storeDir, `_${this.cacheFilePathPrefix}@${this.packageVersion}@${this.packageName}`)
    }
    getSpecificCacheFilePath(packageVersion) {
        return path.resolve(this.storeDir, `_${this.cacheFilePathPrefix}@${packageVersion}@${this.packageName}`)
    }
   
    // 判断当前Package是否存在
    async exists() {
        if( this.storeDir) {
           await this.prepare()
           console.log(this.cacaeFilePath)
           return pathExists(this.cacaeFilePath)
        } else {
       
           return pathExists(this.targetPath)
        }

    }

    // 安装package
    install() {
        return npminstall({
            root: this.targetPath,
            storeDir: this.storeDir,
            registry: getDefaultRegistry(),
            pkgs: [
                { 
                    name: this.packageName, 
                    version: this.packageVersion 
                },
              ],
          })
    }

    // 更新package
    async update() {
        await this.prepare()
        // 1.获取最新npm模块版本号
        const latestPackageVersion =  await getNpmLatestVersion(this.packageName)
        // 2.查询最新版本路径是否存在
        const latestFilePath = this.getSpecificCacheFilePath(latestPackageVersion)
        // 3. 如果不存在更新
        if (!pathExists(latestFilePath)) {
            await npminstall({
                root: this.targetPath,
                storeDir: this.storeDir,
                registry: getDefaultRegistry(),
                pkgs: [
                    { 
                        name: this.packageName, 
                        version: latestPackageVersion
                    },
                  ],
              })
              this.packageVersion = latestPackageVersion
        }
    }

    // 获取入口文件
    getRootFilePath() {
        function _getRootFile(targetPath) {
            // 1.获取package.json所在目录
            const dir = pkgDir(targetPath)
            if (dir) {
                // 2.读取package.json
                const pkgFire = require(path.resolve(dir, 'package.json'))
                // 3.寻找main\lib
                if (pkgFire && (pkgFire.main)) {
                    // 4.路径的兼容（macOs/windows)
                    return formatPath(path.resolve(dir, pkgFire.main))
                }
            }
            return null
        }
        if (this.storeDir) {
            return  _getRootFile(this.cacaeFilePath)
        } else{
            return _getRootFile(this.targetPath)
        }
    }

}

module.exports = Package;